var _ = require('underscore');

var translate = function(source, data, key){
	var me = arguments.callee;
	var transdata;

	if(_.isArray(data)){
		transdata = [];
		_.each(data, function(value, i){
			transdata[i] = me(source, value);
		});
	}else if(_.isObject(data)){
		transdata = {};

		for(var key in data){
			transdata[key] = me(source, data[key], key);
		}
	}else if(_.isString(data)){
		transdata = source[data] || (key && source[key] && source[key][data]) || data;
	}else{
		transdata = data;
	}

	return transdata;
};

var fuse = function(model, i18n, textname, sourcename){
	textname = textname || 'text';
	sourcename = sourcename || 'data';

	var mData = model && model.toJSON && model.toJSON() || (_.isObject(model) && model) || {};
	var text = i18n[textname];
	var source = i18n[sourcename];
	var target;

	if(source){
		target = this.translate(source, mData);
	}

	return _.extend(mData, text, target);
};


module.exports = {
	translate: translate,
	fuse: fuse
};